// 小程序相关的操作类
import axios from 'axios';
import moment from 'moment';
import logger from './logger';


let tokens = {};

let appletMap=new Map();

async function setApplet(appId, appSecret) {
    appletMap.set(appId, appSecret);
}

// 3. 定义异步函数获取access_token
async function getAccessToken(appId) {
    let appSecret = appletMap.get(appId);
    if (!appSecret) {
        return '';
    }
    if (tokens[appId] && moment().isBefore(tokens[appId].expires_time)) {
        return tokens[appId].access_token;
    }
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;
    try {
        const response = await axios.get(url);
        const data = response.data;

        if (data.access_token) {
            logger.info('获取Access Token成功，Access Token:', data.access_token);
            tokens[appId] = {
                access_token: data.access_token,
                expires_time: moment().add(data.expires_in, 'seconds')
            };
            return data.access_token;
        } else {
            logger.error('Failed to get access token:', data);
            return '';
        }
    } catch (error) {
        logger.error('Error fetching access token:', error);
        return '';
    }
}

async function getOpenId(appId, code) {
    // await getAccessToken(appId);
    // if (!tokens[appId] || !tokens[appId].access_token) {
    //     return { code: 0, msg: '获取access_token失败' };
    // }
    let appSecret = appletMap.get(appId);
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
    try {
        let res = await axios.get(url);
        if (res) {
            if (res.data.openid) {
                return { code: 1, openid: res.data.openid };
            } else {
                return { code: 0, msg: res.data.errmsg };
            }
        }
    } catch (ex) {
        return { code: 0, msg: ex.message };
    }
}

export { getOpenId };
